﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data.Services.Client;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace McCloudCore
{
    class LogEntity : TableStorageEntity
    {
        public DateTime Time { get; set; }
        public string Message { get; set; }
        public string InstanceId { get; set; }
        public string Category { get; set; }

        public LogEntity(string message, string category)
        {
            Message = message;
            Category = category;
            Time = DateTime.UtcNow;
            InstanceId = RoleEnvironment.CurrentRoleInstance.Id;
            PartitionKey = RoleEnvironment.DeploymentId;
            RowKey = (DateTime.MaxValue.Ticks - Time.Ticks).ToString("d19");
        }
    }

    class LogModel : TableStorageDataServiceContext
    {
        public readonly string name = "log";
        public IQueryable<LogEntity> log { get { return this.CreateQuery<LogEntity>(this.name); } }
        public LogModel(StorageAccountInfo accountInfo) : base(accountInfo) { }
    }
    
    public class Log
    {
        private static void Write(string message, string category)
        {
            if (RoleEnvironment.GetConfigurationSettingValue("Log") == "false") return;
            System.Diagnostics.Trace.WriteLine(message, category);
            StorageAccountInfo account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
            TableStorage tableStorage = TableStorage.Create(account);
            tableStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
            TableStorage.CreateTablesFromModel(typeof(LogModel), account);
            LogModel data = new LogModel(account);
            data.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));            
            LogEntity item = new LogEntity(message, category);
            data.AddObject(data.name, item);
            data.SaveChanges();
        }

        public static void WriteError(string message) { Write(message, "Error"); }
        public static void WriteInformation(string message) { Write(message, "Information"); }
        public static void WriteWarning(string message) { Write(message, "Warning"); }
    }
}
